/*
 * SendSocketJuzEvent.cpp
 *
 *  Created on: 2017年6月6日
 *      Author: orange
 */

#include "SendSocketJuzEvent.h"

#include <cstring>

#include "../PublicDefine.h"

const char* SendSocketJuzEvent::mEventName = "SendSocketJuzEvent";
SendSocketJuzEvent::SendSocketJuzEvent(int fd,char what,char type,char arg1,char arg2,int nLen,char *pData,const char *evName):SocketInfoJuzEvent(fd,what,type,arg1,arg2,nLen,pData,evName)
{
	setType(_NotInterruptDelete);//不可被中断　与　截取
	this->nLen = this->nLen + SOCKETHEAD;//send要加上这个

	encryptionPro = NULL;
	sendFinshPro = NULL;

	RCV_EN = NULL;
	key = NULL;
	sendData = NULL;
	isFinsh = false;
}

bool SendSocketJuzEvent::getFinsh()
{
	return isFinsh;
}

SendSocketJuzEvent::~SendSocketJuzEvent() {
	// TODO Auto-generated destructor stub
}
void SendSocketJuzEvent::RC4_En(int nLen,char *src,char *out)
{
	if(RCV_EN != NULL)
	{
		RCV_EN(key,nLen,src,out);
	}
}
void SendSocketJuzEvent::setEncryptionPro(WorkPro encryptionPro) {
	this->encryptionPro = encryptionPro;
}
void SendSocketJuzEvent::setSendFinshPro(SendFinshPro sendFinshPro) {
	this->sendFinshPro = sendFinshPro;
}

void SendSocketJuzEvent::setKey(char* key) {
	this->key = key;
}

void SendSocketJuzEvent::setRcvEn(RC4_EncryptionPro rcvEn) {
	RCV_EN = rcvEn;
}
//设置加密
void SendSocketJuzEvent::setEncryption() {
	sendData = new char[getLen()];
	memset(sendData,0,getLen());
	//赋值
	JUZ_SOCKET_DATA socketData;
	socketData.nLen = getLen();
	socketData.what = getWhat();
	socketData.type = getType();
	socketData.arg1 = getArg1();
	socketData.arg2 = getArg2();
	socketData.sum = (socketData.nLen & 0xff) + socketData.what + socketData.type + socketData.arg1 + socketData.arg2;

	char *pDataSocketHead = (char*)&socketData;
	//数据打乱
	for(int i = 0 ; i < SOCKETHEAD ; i += 2)
	{
		//交换
		if((i + 1) < SOCKETHEAD) //不要越界了
		{
			char swap;
			swap = *(pDataSocketHead + i + 1);
			*(pDataSocketHead + i + 1) = *(pDataSocketHead + i);   //2 = 1
			*(pDataSocketHead + i) = swap;     //1 = 2
		}

	}
	//头部信息加密
	RCV_EN(key,SOCKETHEAD,pDataSocketHead,sendData);

	//尾部信息copy
	memcpy(sendData + SOCKETHEAD,getData(),getLen() - SOCKETHEAD);

	//调用自定义加密
	if(encryptionPro != NULL)
	{
		encryptionPro(this);
	}
}

void SendSocketJuzEvent::finsh(int nState) {
	//完成
	if(sendFinshPro != NULL)
	{
		sendFinshPro(this,nState);
	}

	if(sendData != NULL)
	{
		delete[] sendData;
	}
	isFinsh = true;
}
char* SendSocketJuzEvent::getSendData() const {
	return sendData;
}
void SendSocketJuzEvent::setPublicEncryption()
{
	this->encryptionPro = [](SendSocketJuzEvent* sendEv){
				char *sendPdata = sendEv->getSendData() + SOCKETHEAD;
				sendEv->RC4_En(sendEv->getLen() - SOCKETHEAD,sendEv->getData(),sendPdata);
			};
}
